package openjdk.future;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
        // 创建一个ExecutorService
        ExecutorService executor = Executors.newCachedThreadPool();
        FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
            public String call() throws Exception {
                try {
                    Thread.sleep(9 * 1000);
                    return "Hello world";
                } catch (Exception e) {
                    throw new Exception("Callable terminated with Execption");
                }
            }
        });

        System.out.println("before execute... ");
        executor.execute(future);
        System.out.println("after execute...");
        long start = System.currentTimeMillis();
        System.out.println("before try...");

        try {
            System.out.println("before sleep");
            Thread.sleep(2000);
            System.out.println("before future get");
            String result = future.get();
            long last = System.currentTimeMillis() - start;
            System.out.println("result is " + result + ", time is " + last);
        } catch (InterruptedException ie) {
            future.cancel(true);
            ie.printStackTrace();
        } catch (java.util.concurrent.ExecutionException ee) {
            future.cancel(true);
            ee.printStackTrace();
        } finally {
            System.out.println("shut down the executor");
            executor.shutdown();
        }
        System.out.println("The get value is return");
        System.out.println("Hello World Over!");
    }
}
